﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Journal.Common.Extensions;
using Journal.Common.Modules;
using Journal.Domain.IDomainServices;
using Journal.Domain.Models;
using Journal.Front.Presentation.Models.AccountModels;
using System.Web.Security;
using Journal.Front.Presentation.PresentationServicesInterfaces;
using Tools.Security;

namespace Journal.Front.Presentation.PresentationServices
{
    public class AccountPresentationService : IAccountPresentationService
    {
        private readonly IUserDomainService userDomainService;

        public AccountPresentationService(IUserDomainService userDomainService)
        {
            this.userDomainService = userDomainService;
        }

        public AccountModel CreateAccountModel()
        {
            return new AccountModel();
        }

        public bool LogOn(AccountModel model)
        {
            string login = model.Login;
            User user = userDomainService.GetUserByLogin(login);
            if (user != null)
            {
                string salt = user.PasswordSalt;
                string password = RijndaelAlgoritm.Encrypt(model.Password, "a2N8zQIZUoAW2Xy7csfyI6McSu");
                if (user.Password.Equals(password))
                {
                    IList<Role> role = user.Roles.Count == 0 ? null : user.Roles;
                    RegisterAuthCookie(user.Id, user.Login, false, role, true);
                    return true;
                }
            }

            return false;
        }

        private void RegisterAuthCookie(long id, string name, bool writeAccess, IEnumerable<Role> role, bool rememberMe)
        {
            string roles = role.Aggregate(string.Empty, (current, item) => string.Concat(current, ",", item.Name));
            roles = roles.Substring(1);
            var ticket = new FormsAuthenticationTicket(1, id + "/" + name + "/" + writeAccess, DateTime.Now, rememberMe ? DateTime.Now.AddYears(20) : DateTime.Now.AddHours(1), rememberMe, roles, FormsAuthentication.FormsCookiePath);
            var hashCookies = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies) { Expires = DateTime.Now.AddYears(20), HttpOnly = true };
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
}